<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUserGrade extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('user', function ($table) {
            $table->string('grade', 4)->nullable()->after('class_id');
        });
        $users = \App\Model\User::where('class_id', '!=', null)->get();
        foreach ($users as $user) {
            $class = $user->class->name;
            if(starts_with($class, '2016')){
                $grade = '2016';
            }else{
                $grade = '20' . substr($class, 0, 2);
            }
            $user->update(['grade' => $grade]);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('user', function ($table) {
            $table->dropColumn('grade');
        });
    }
}
